﻿var hangLength = -1,
lieLength = -1;
var editallow = 0;
var firstload = 1;
function uploadTableStyle(cellpadding, cellspacing, border, bordercollapse, bordercolor) {
    if (editallow != 1) {
        alert("此小工具添加者没有给予您编辑权限");
        return false
    }
    var state = wave.getState();
    var viewId = wave.getViewer().getId();
    var delta = {};
    var lastHang = parseInt(state.get('table.hang', '-1'));
    var lastLie = parseInt(state.get('table.lie', '-1'));
    if (cellpadding != parseInt(state.get('table.cellpadding', '0'))) delta['table.cellpadding'] = cellpadding;
    if (cellspacing != parseInt(state.get('table.cellspacing', '0'))) delta['table.cellspacing'] = cellspacing;
    if (border != parseInt(state.get('table.border', '0'))) delta['table.border'] = border;
    if (bordercollapse != state.get('table.bordercollapse', 'collapse')) delta['table.bordercollapse'] = bordercollapse;
    if (bordercolor != state.get('table.bordercolor', '#3300FF')) delta['table.bordercolor'] = bordercolor;
    if (lastHang != hangLength || lastLie != lieLength) {
        delta['table.hang'] = hangLength;
        delta['table.lie'] = lieLength
    }
    delta['sys.sync'] = -1;
    delta['sys.submituser'] = viewId;
    state.submitDelta(delta)
}
function downTableStyle() {
    var state = wave.getState();
    $("#get_hang").val(state.get('table.hang', '-1'));
    $("#get_lie").val(state.get('table.lie', '-1'));
    $("#get_cellpadding").val(state.get('table.cellpadding', '0'));
    $("#get_cellspacing").val(state.get('table.get_cellspacing', '0'));
    $("#get_border").val(state.get('table.border', '1'));
    var numBordercollapse = state.get('table.bordercollapse', 'collapse');
    if (numBordercollapse == 'collapse') document.getElementById('get_bordercollapse').checked = true;
    else document.getElementById('get_bordercollapse').checked = false;
    var colorstr = state.get('table.bordercolor', '#3300FF');
    if (colorstr == 0) colorstr = '#3300FF';
    var objbordercolor = document.getElementById('get_bordercolor');
    $('#get_bordercolor').css('background-color', colorstr);
    try {
        objbordercolor.options.selectedIndex = getbyid('get_bordercolor' + colorstr).index;
        objbordercolor.options.selected = true
    } catch(e) {}
}
function uploadTableText(text, style, ID, hang, hangHeight, lie, lieWidth) {
    if (editallow != 1) {
        alert("此小工具添加者没有给予您编辑权限");
        return false
    }
    var state = wave.getState();
    var viewId = wave.getViewer().getId();
    var delta = {};
    delta['data.' + ID] = text;
    delta['style.' + ID] = style;
    delta['hangHeight.' + hang] = hangHeight;
    delta['lieWidth.' + lie] = lieWidth;
    delta['sys.sync'] = ID;
    delta['sys.submituser'] = viewId;
    state.submitDelta(delta)
}
function downTableText(ID, process) {
    var state = wave.getState();
    var style = state.get('style.' + ID, 'text-decoration: none;');
    var text = state.get('data.' + ID, '&nbsp;');
    var hang = parseInt(ID / parseInt(lieLength));
    var lie = ID - parseInt(lieLength) * parseInt(hang);
    var hangHeight = state.get('hangHeight.' + hang, '30');
    var lieWidth = state.get('lieWidth.' + lie, '30');
    var td = $('td', $('#mytable table tr').eq(hang)).eq(lie);
    td.html(text);
    td.attr('style', style);
    $('td', $('#mytable table tr').eq(0)).eq(lie).attr('width', lieWidth);
    $('td', $('#mytable table tr').eq(hang)).eq(0).attr('height', hangHeight)
}
function downAllText() {
    var state = wave.getState();
    if (hangLength != -1 && lieLength != -1) {
        var maxid = hangLength * lieLength;
        for (var i = 0; i < maxid; i++) downTableText(i, 0)
    }
}
function addListen() {
    $('#mytable table tr').each(function(hang) {
        $('td', $(this)).each(function(lie) {
            $(this).click(function() {
                $('.stepLi').each(function(index) {
                    if ($(this).attr('id') != 'step_3') $(this).slideUp('fast',
                    function() {
                        gadgets.window.adjustHeight()
                    });
                    else $(this).slideDown('fast',
                    function() {
                        gadgets.window.adjustHeight()
                    })
                });
                gadgets.window.adjustHeight();
                syncTextBox(hang, lie, 2)
            })
        })
    })
}
function step_1_next_load() {
    hangLength = parseInt($("#get_hang").val());
    lieLength = parseInt($("#get_lie").val());
    if (hangLength == -1 && lieLength == -1) if (editallow == 1) $('#guide').show('fast',
    function() {
        gadgets.window.adjustHeight()
    });
    else;
    else {
        $('#guide').css('display', 'none');
        $('#mytable').html('<table></table>');
        var table = $('#mytable table');
        var padstr = '&nbsp;';
        if (numBorder == 0) padstr = '|_';
        for (var i = 0; i < hangLength; i++) {
            var str = '<tr>';
            for (var t = 0; t < lieLength; t++) {
                str += '<td>' + padstr + '</td>'
            }
            str += '</tr>';
            $('#mytable table').append(str)
        }
        var numCellpadding = parseInt($("#get_cellpadding").val());
        var numCellspacing = parseInt($("#get_cellspacing").val());
        var numBorder = parseInt($("#get_border").val());
        var numBordercollapse = 'collapse';
        if (document.getElementById('get_bordercollapse').checked) numBordercollapse = 'collapse';
        else numBordercollapse = 'separate';
        $('#mytable table').attr('cellpadding', numCellpadding);
        $('#mytable table').attr('cellspacing', numCellspacing);
        $('#mytable table').attr('border', numBorder);
        $('#mytable table').attr('bordercolor', $('#get_bordercolor').val());
        $('#mytable table').css('border-collapse', numBordercollapse);
        downAllText()
    }
}
function onLoading() {
    var state = wave.getState();
    var viewId = wave.getViewer().getId();
    var hostId = wave.getHost().getId();
    downTableStyle();
    if (viewId == hostId) {
        editallow = 1;
        $('#menuEdit').css('color', '#000');
        document.getElementById('global_edit_allow').disabled = false
    } else {
        document.getElementById('global_edit_allow').disabled = true;
        if (state.get('sys.editallow', 0) == 1) {
            editallow = 1;
            document.getElementById('global_edit_allow').checked = true
        } else {
            document.getElementById('global_edit_allow').checked = false;
            $('#menuEdit').css('color', '#CCC')
        }
    }
    step_1_next_load();
    gadgets.window.adjustHeight()
}
function checkLimit(val, vmin, vmax, vmsg) {
    if (isNaN(val) || isNaN(vmin) || isNaN(vmax) || vmin > vmax || vmsg == '') {
        alert("请填写完全部参数");
        return false
    }
    if (val > vmin && val < vmax) return true;
    else {
        alert(vmsg);
        return false
    }
}
function syncTextBox(hang, lie, mode) {
    try {
        $('#readBox').unbind('click')
    } catch(e) {}
    $('#readBox').click(function() {
        syncTextBox(hang, lie, 1)
    });
    if (mode == 1) {
        var style = $('#get_text').attr('style');
        var text = $('#get_text').val();
        var hangHeight = $('#get_hangHeight').val();
        var lieWidth = $('#get_lieWidth').val();
        if (!checkLimit(hangHeight, 0, 1001, '请输入合适的行高[1,1000]') || !checkLimit(lieWidth, 0, 1001, '请输入合适的列宽[1,1000]')) return false;
        $('td', $('#mytable table tr').eq(hang)).eq(0).attr('height', hangHeight);
        $('td', $('#mytable table tr').eq(0)).eq(lie).attr('width', lieWidth);
        var td = $('td', $('#mytable table tr').eq(hang)).eq(lie);
        td.html(text);
        td.attr('style', style);
        ID = parseInt(hang) * parseInt(lieLength) + parseInt(lie);
        uploadTableText(text, style, ID, hang, hangHeight, lie, lieWidth)
    } else {
        var hangHeight = $('td', $('#mytable table tr').eq(hang)).eq(0).attr('height');
        if (hangHeight > 0) $('#get_hangHeight').val(hangHeight);
        else $('#get_hangHeight').val('30');
        var lieWidth = $('td', $('#mytable table tr').eq(0)).eq(lie).attr('width');
        if (lieWidth > 0) $('#get_lieWidth').val(lieWidth);
        else $('#get_lieWidth').val('30');
        var td = $('td', $('#mytable table tr').eq(hang)).eq(lie);
        var style = td.attr('style');
        var text = td.html();
        if (text == '') text = '&nbsp;';
        $('#get_text').val(text);
        if (style == undefined) {
            style = "text-decoration: none;"
        }
        $('#get_text').attr('style', style);
        loadtextstyle()
    }
    gadgets.window.adjustHeight()
}
function step_1_next(door) {
    if (door == 0 && editallow != 1) {
        alert("此小工具添加者没有给予您编辑权限");
        return false
    }
    var numHang = parseInt($("#get_hang").val());
    var numLie = parseInt($("#get_lie").val());
    var numCellpadding = parseInt($("#get_cellpadding").val());
    var numCellspacing = parseInt($("#get_cellspacing").val());
    var numBorder = parseInt($("#get_border").val());
    var numBordercollapse = 'collapse';
    if (document.getElementById('get_bordercollapse').checked) numBordercollapse = 'collapse';
    else numBordercollapse = 'separate';
    if (!checkLimit(numHang, 0, 31, "请输入合适的行") || !checkLimit(numLie, 0, 31, "请输入合适的列") || !checkLimit(numCellpadding, -1, 101, "请输入合适的单元格填充") || !checkLimit(numCellspacing, -1, 101, "请输入合适的单元格边距") || !checkLimit(numBorder, -1, 101, "请输入合适的表格边框")) return false;
    if (hangLength == -1 && lieLength == -1) {
        $('#mytable').html('<table></table>');
        var table = $('#mytable table');
        hangLength = numHang;
        lieLength = numLie;
        var padstr = '&nbsp;';
        if (numBorder == 0) padstr = '|_';
        for (var i = 0; i < numHang; i++) {
            var str = '<tr>';
            for (var t = 0; t < numLie; t++) {
                if (i == 0) str += '<td>' + padstr + '</td>';
                else str += '<td width="30">' + padstr + '</td>'
            }
            str += '</tr>';
            $('#mytable table').append(str)
        }
        addListen()
    } else {
        if (numHang != hangLength || numLie != lieLength) {
            try {
                $('#mytable table tr').each(function() {
                    $('td', $(this)).each(function() {
                        $(this).unbind('click')
                    })
                })
            } catch(e) {}
            if (numHang > hangLength) {
                var padstr = '&nbsp;';
                if (numBorder == 0) padstr = '|_';
                for (var i = 0; i < numHang - hangLength; i++) {
                    var str = '<tr>';
                    for (var t = 0; t < lieLength; t++) {
                        str += '<td>' + padstr + '</td>'
                    }
                    str += '</tr>';
                    $('#mytable table').append(str)
                }
            } else {
                var str = '#mytable table tr:eq(' + numHang + ')';
                for (var i = numHang; i < hangLength; i++) {
                    $(str).remove()
                }
                document.getElementById('step_2_next').disabled = true
            }
            hangLength = numHang;
            if (numLie > lieLength) {
                var padstr = '&nbsp;';
                if (numBorder == 0) padstr = '|_';
                for (var i = 0; i < hangLength; i++) {
                    var str = '';
                    for (var t = 0; t < numLie - lieLength; t++) {
                        str += '<td>' + padstr + '</td>'
                    }
                    $('#mytable table tr').eq(i).append(str)
                }
            } else {
                for (var i = 0; i < hangLength; i++) {
                    var str = '#mytable table tr:eq(' + i + ') td:eq(' + numLie + ')';
                    for (var t = numLie; t < lieLength; t++) $(str).remove()
                }
                document.getElementById('step_2_next').disabled = true
            }
            lieLength = numLie;
            if (editallow == 1) addListen()
        }
    }
    $('#mytable table').attr('cellpadding', numCellpadding);
    $('#mytable table').attr('cellspacing', numCellspacing);
    $('#mytable table').attr('border', numBorder);
    $('#mytable table').attr('bordercolor', $('#get_bordercolor').val());
    $('#mytable table').css('border-collapse', numBordercollapse);
    if (door == 0) uploadTableStyle(numCellpadding, numCellspacing, numBorder, numBordercollapse,$('#get_bordercolor').val());
    if (editallow == 1) {
        $('#step_1').slideUp("fast",
        function() {
            gadgets.window.adjustHeight()
        });
        $('#step_2').slideDown("fast",
        function() {
            gadgets.window.adjustHeight()
        })
    } else {
        $('#guide').hide('fast',
        function() {
            gadgets.window.adjustHeight()
        })
    }
}
function step_2_next() {
    $('#step_2').slideUp("fast",
    function() {
        gadgets.window.adjustHeight()
    });
    $('#step_3').slideDown("fast",
    function() {
        gadgets.window.adjustHeight()
    })
}
function step_3_next() {
    $('#step_3').slideUp("fast",
    function() {
        gadgets.window.adjustHeight()
    });
    $('#step_4').slideDown("fast",
    function() {
        gadgets.window.adjustHeight()
    })
}
function step_4_submit() {
    $('#guide').hide('fast',
    function() {
        gadgets.window.adjustHeight()
    });
    try {
        $('#mytable table tr').each(function() {
            $('td', $(this)).each(function() {
                $(this).unbind('click')
            })
        })
    } catch(e) {}
    wave.getState().submitDelta({
        'sys.sync': '-10'
    })
}
function syncState() {
    if (firstload == 1) {
        onLoading();
        firstload = 0;
        return true
    }
    var state = wave.getState();
    var viewId = wave.getViewer().getId();
    var lastId = state.get('sys.submituser', '0');
    var sync = state.get('sys.sync', '-5');
    if (viewId == lastId);
    else {
        if (sync == -1) {
            downTableStyle();
            step_1_next(1)
        } else if (sync == -2) {
            editallow = state.get('sys.editallow', 0);
            if (editallow == 1) {
                document.getElementById('global_edit_allow').checked = true;
                $('#menuEdit').css('color', '#000')
            } else {
                $('#mytable table tr').each(function() {
                    $('td', $(this)).each(function() {
                        $(this).unbind('click')
                    })
                });
                $('#guide').hide('fast',
                function() {
                    gadgets.window.adjustHeight()
                });
                document.getElementById('global_edit_allow').checked = false;
                $('#menuEdit').css('color', '#CCC')
            }
        } else if (sync >= 0) downTableText(sync, 0)
    }
    gadgets.window.adjustHeight()
}
$(function() {
    makeselectcolor('get_bordercolor');
    makeselectcolor('get_bgcolor');
    makeselectcolor('get_txtcolor');
    $('#get_align,#get_txtcolor,#get_txtcolor,#get_bgcolor,#get_fontsize,#get_em,#get_strong,#get_underline').change(function() {
        settextstyle()
    });
    $('#get_bordercolor').change(function() {
        $(this).css('background-color', $('#get_bordercolor').val())
    });
    $('.step_next').each(function(index) {
        $(this).click(function() {
            switch (index) {
            case 0:
                step_1_next(0);
                break;
            case 1:
                step_2_next();
                break;
            case 2:
                step_3_next();
                break;
            case 3:
                step_4_submit();
                break
            }
        })
    });
    $('.step_back').each(function(index) {
        $(this).click(function() {
            $('.stepLi').eq(index).slideDown("fast",
            function() {
                gadgets.window.adjustHeight()
            });
            $('.stepLi').eq(index + 1).slideUp("fast",
            function() {
                gadgets.window.adjustHeight()
            });
            gadgets.window.adjustHeight()
        })
    });
    $('#step_1 ul li > input[type=text]').each(function() {
        $(this).change(function() {
            var v = parseInt($(this).val());
            if (isNaN(v)) v = '0';
            $(this).val(v)
        })
    });
    $('#get_hangHeight,#get_lieWidth').each(function() {
        $(this).change(function() {
            var v = parseInt($(this).val());
            if (isNaN(v)) v = '30';
            $(this).val(v)
        })
    });
    $('#lang_en').click(function() {
        $('.lang_zh-cn').css('display', 'none');
        $('.lang_en').css('display', 'inline')
    });
    $('#lang_zh-ch').click(function() {
        $('.lang_en').css('display', 'none');
        $('.lang_zh-cn').css('display', 'inline')
    });
    $('#menuEdit').click(function() {
        if (editallow != 1) {
            $('#guide').hide('fast',
            function() {
                gadgets.window.adjustHeight()
            });
            alert("此小工具已被添加者锁定");
            return false
        } else $('#guide').toggle('fast',
        function() {
            gadgets.window.adjustHeight();
            try {
                $('#mytable table tr').each(function() {
                    $('td', $(this)).each(function() {
                        $(this).unbind('click')
                    })
                })
            } catch(e) {}
            if ($('#guide').css('display') == 'block') $('.stepLi').each(function() {
                if ($(this).attr('id') != 'step_2') $(this).slideUp('fast',
                function() {
                    gadgets.window.adjustHeight()
                });
                else $(this).slideDown('fast',
                function() {
                    gadgets.window.adjustHeight()
                })
            });
            addListen()
        })
    });
    $('#global_edit_allow').change(function() {
        var temp = 0;
        var viewId = wave.getViewer().getId();
        if (document.getElementById('global_edit_allow').checked == true) temp = 1;
        else temp = 0;
        wave.getState().submitDelta({
            'sys.editallow': temp,
            'sys.sync': '-2',
            'sys.submituser': viewId
        })
    })
});
function init() {
    if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(syncState)
    }
}
gadgets.util.registerOnLoadHandler(init);